package com.dingshi.security;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.dingshi.security.adapter.HistoryAdapter;
import com.dingshi.security.adapter.OnDutyAdapter;
import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.RepairApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.entity.Track;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.LoadDialog;

public class RepairHistoryListActivity extends BaseActivity implements
		OnClickListener {
	private static final int DATE_DIALOG_ID = 2019;
	protected static final int ID_LOADING = 3000;
	private Button btn_back;
	private TextView title_text;
	private ListView listView;
	private InputMethodManager inputMethodManager;
	private EditText edit_start_time;
	private EditText edit_end_time;
	private Spinner edit_on_duty;
	private Button btn_start;
	private TextView tips;
	private TextView list_title_device;
	private TextView list_title_shangbao_date;
	private TextView list_title_status;
	private TextView list_title_process;
	private EditText currentEdit;
	private HistoryAdapter adapter;
	protected ArrayList<Track> list;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.repair_history);

		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		initTitle();
		initComponents();
		registerButton();

		listView.setCacheColorHint(Color.TRANSPARENT);
		listView.setDividerHeight(0);
		getHistoryList(SettingLoader.getGuardNum(this), SettingLoader.getLoginUserType(this));
		
		ondutyAdapter = new OnDutyAdapter(this,SettingLoader.getGuardName(this));
		edit_on_duty.setAdapter(ondutyAdapter);

	}

	private void getHistoryList(String guardNum, String deprNum) {

		RepairApi api = new RepairApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":[{"__type":"DiaryReturn:r","c":"aaa","t":"01:59:05"}],"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							break;
						case 1:// 数组
							JSONArray array = jsonEntity.getJSONArray("d");
							if (array != null) {
								list = new ArrayList<Track>();
								Track track = null;
								Log.e("array", "array is " + array.length());
								for (int i = 0; i < array.length(); i++) {
									track = new Track();
									JSONObject opt = (JSONObject) array.opt(i);
									track.setOddNum(opt.getString("d"));
									track.setArea(opt.getString("a"));
									track.setName(opt.getString("n"));
									track.setStatus(opt.getString("s"));
									Log.e("status", "status is "
											+ opt.getString("s"));
									track.setReportDate(opt.getString("t"));
									if (opt.has("tc")) {
										track.setFinishDate(opt.getString("tc"));
									}
									track.setDeviceName(opt.getString("e"));
									list.add(track);
								}
								Log.i("Track", "size is " + list.size());
							}

							updateList();

							break;
						case -1:// 错误
							dismissDialog(ID_LOADING);
							updateList();
							break;

						default:
							dismissDialog(ID_LOADING);
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				updateList();
			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
		});
		api.getRepairList(1, SettingLoader.getGuardNum(this), SettingLoader
				.getLoginUserType(this));

	}

	private void updateList() {
		ArrayList<Track> mList = handle(list);
		if (mList != null && mList.size() > 0) {
			tips.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			Log.e("list", "diary count is " + mList.size());
			adapter = new HistoryAdapter(RepairHistoryListActivity.this, mList);
			adapter.setType(HistoryAdapter.type_alarm_service);
			listView.setAdapter(adapter);
			
		} else {
			tips.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
		}
	}

	private ArrayList<Track> handle(ArrayList<Track> list) {
		ArrayList<Track> mList = new ArrayList<Track>();
		for(Track track : list) {
			Log.e("status", "status is " + track.getStatus());
			if("5".equals(track.getStatus())) {
				mList.add(track);
			}
		}
		return mList;
	}
	
	private void initTitle() {
		btn_back = (Button) findViewById(R.id.btn_back);
		title_text = (TextView) findViewById(R.id.title_text);
		title_text.setText("历史报修查询");

	}

	private void registerButton() {
		btn_back.setOnClickListener(this);
		edit_start_time.setOnClickListener(this);
		edit_end_time.setOnClickListener(this);
		btn_start.setOnClickListener(this);
	}

	private void initComponents() {
		listView = (ListView) findViewById(R.id.listView1);

		edit_start_time = (EditText) findViewById(R.id.edit_start_time);
		edit_end_time = (EditText) findViewById(R.id.edit_end_time);
		edit_on_duty = (Spinner) findViewById(R.id.edit_on_cuty);
		btn_start = (Button) findViewById(R.id.btn_start);
		tips = (TextView) findViewById(R.id.tips);
		// list title
		list_title_device = (TextView) findViewById(R.id.list_title_device);
		list_title_shangbao_date = (TextView) findViewById(R.id.list_title_shangbao_date);
		list_title_status = (TextView) findViewById(R.id.list_title_status);
		list_title_process = (TextView) findViewById(R.id.list_title_process);

		inputMethodManager.hideSoftInputFromWindow(edit_start_time
				.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		inputMethodManager.hideSoftInputFromWindow(edit_end_time
				.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

		list_title_device.setText("设备名称");
		list_title_shangbao_date.setText("上报日期");
		list_title_status.setText("完毕日期");
		list_title_process.setText("值班人员");
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			int mYear = 0,
			mMonth = 0,
			mDay = 0;
			Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);

			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);

		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, getResources().getString(
					R.string.login_loading));
			return dialog;
		default:
			break;
		}

		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
	}

	// the callback received when the user 'sets' the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			currentEdit.setText(new StringBuilder().append(year + "-").append(
					monthOfYear + 1).append("-").append(dayOfMonth));

		}
	};
	private OnDutyAdapter ondutyAdapter;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			super.onBackPressed();
			break;
		case R.id.btn_start:
			String start_time = edit_start_time.getText().toString();
			String end_time = edit_end_time.getText().toString();
			String onduty = list.get(edit_on_duty.getSelectedItemPosition()).getName();//TODO
			updateUIbyCondition(start_time, end_time, onduty);

			break;
		case R.id.edit_start_time:
			currentEdit = edit_start_time;
			showDialog(DATE_DIALOG_ID);
			break;
		case R.id.edit_end_time:
			currentEdit = edit_end_time;
			showDialog(DATE_DIALOG_ID);
			break;
		default:
			break;
		}
	}

	private void updateUIbyCondition(String start_time, String end_time,
			String onduty) {
		ArrayList<Track> mList = null;
		if (list != null) {
			mList = new ArrayList<Track>();
			for (Track track : list) {
				if (onduty.equals(track.getName())) {
					if (track.getReportDate() != null) {
						if (track.getReportDate().compareTo(start_time) > 0
								&& track.getReportDate().compareTo(end_time) < 0) {
							mList.add(track);
						}
					}
				}
			}
		}
		if (mList != null && mList.size() > 0) {
			tips.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			Log.e("list", "diary count is " + mList.size());
			adapter = new HistoryAdapter(RepairHistoryListActivity.this, mList);
			adapter.setType(HistoryAdapter.type_alarm_service);

			listView.setAdapter(adapter);
		} else {
			tips.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
		}
	}
}
